package org.dreamwork.jasmine2.sample.page;

import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.web.controls.Page;
import sample.data.Product;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-10-15
 * Time: 16:28:45
 */
public class DataGridPage extends Page {
    protected List<Product> list;

    @Override
    public void onPagePreload (Page page) throws EventException {
        list = new ArrayList<Product> ();
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=d:\\tmp\\Northwind.mdb";
        try {
            Class.forName (driver);
            Connection conn = DriverManager.getConnection (url, "", "");
            try {
                String sql =
                        "SELECT a.[产品ID] as product_id, a.[产品名称] as product_name, b.[公司名称] as companyName, c.[类别名称]  as categoryName, \n" +
                        "       a.[单位数量] as unit, a.[单价] as price, a.[库存量] as store_count\n" +
                        "  from [产品] a, [供应商] b, [类别] c\n" +
                        " where a.[供应商ID] = b.[供应商ID]\n" +
                        "   and a.[类别ID] = c.[类别ID]";
                Statement stmt = conn.createStatement ();
                ResultSet rs = stmt.executeQuery (sql);
                while (rs.next ()) {
                    Product product = new Product ();
                    product.setId (rs.getInt ("product_id"));
                    product.setName (rs.getString ("product_name"));
                    product.setSupplier (rs.getString ("companyName"));
                    product.setCategory (rs.getString ("categoryName"));
                    product.setUnit (rs.getString ("unit"));
                    product.setPrice (rs.getDouble ("price"));
                    product.setStore (rs.getDouble ("store_count"));
                    list.add (product);
                }
            } finally {
                conn.close ();
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    @Override
    public void onPageLoadCompleted (Page page) throws EventException {
        try {
            dataBind ();
        } catch (Throwable throwable) {
            throwable.printStackTrace ();
        }
    }
}